package com.richie696.connect;


import java.net.Socket;
import java.util.Objects;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class CatalinaExecutor {

    private String name;

    private String namePrefix;

    private int corePoolSize;

    private int maximumQueueSize;

    private long keepAliveTime;

    private int maxThreads;

    private ThreadPoolExecutor executor;

    public CatalinaExecutor init(String name, String namePrefix, int corePoolSize,
                                 int maximumQueueSize, long keepAliveTime, int maxThreads) {
        if (Objects.nonNull(executor)) {
            return this;
        }
        this.name = name;
        this.namePrefix = namePrefix;
        this.corePoolSize = corePoolSize;
        this.maximumQueueSize = maximumQueueSize;
        this.keepAliveTime = keepAliveTime;
        this.maxThreads = maxThreads;
        return this;
    }

    public void build() {
        if (Objects.nonNull(executor)) {
            return;
        }
        executor = new ThreadPoolExecutor(
                corePoolSize,
                maxThreads,
                keepAliveTime,
                TimeUnit.MILLISECONDS,
                new ArrayBlockingQueue<>(maximumQueueSize),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy()
        );
    }

    public String getName() {
        return name;
    }

    public CatalinaExecutor setName(String name) {
        this.name = name;
        return this;
    }

    public String getNamePrefix() {
        return namePrefix;
    }

    public int getCorePoolSize() {
        return corePoolSize;
    }

    public int getMaximumQueueSize() {
        return maximumQueueSize;
    }

    public long getKeepAliveTime() {
        return keepAliveTime;
    }

    public void shutdown() {
        this.executor.shutdown();
    }

    public boolean isShutdown() {
        return this.executor.isShutdown();
    }

    public void execute(RequestProcessor processor) {
        this.executor.execute(processor);
    }
}
